package com.adee.gulimall.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Arrays;

/**
 * cors跨域处理，可以使用GlobalFilter方式，也可以使用配置文件方式，因为有多个默认的系统过滤器和
 * 自定义过滤器，涉及到order优先级，因此，我们使用GlobalFilter方式处理跨域，可以很方便的控制优先级，
 * 跨域过滤器的优先级定为最低，即order最大，放到最后，防止被其他过滤器把header覆盖了。
 *
 * 配置文件方式：
 * spring:
 *   cloud:
 *     gateway:
 *       globalcors:
 *         corsConfigurations:
 *           '[/**]':
 *             allowedOrigins: "*"
 *             allowedMethods: "*"
 *             allowedHeaders: "*"
 *         default-filters[0]: DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentia
 */
@Component
@Slf4j
public class Global_4_CorsFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setAccessControlAllowOrigin("*");
//        response.getHeaders().setAccessControlAllowHeaders("*");
        response.getHeaders().setAccessControlAllowCredentials(true);
        response.getHeaders().setAccessControlAllowMethods(Arrays.asList(HttpMethod.GET, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PUT));
        response.getHeaders().setAccessControlMaxAge(Duration.ofDays(30)); // 30天内不用发探测请求，该网站的请求都能跨域

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 指定此过滤器位于NettyWriteResponseFilter之后
        // 即待处理完响应体后接着处理响应头
//        return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER + 1;
        return OrderNum.CorsFilterOrder;
    }
}
